package com.qz.center.file.server.controller;

import com.qz.center.file.server.common.Result;
import com.qz.center.file.server.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author gbx
 */
@Api(description = "文件上传服务")
@RestController
@RequestMapping("/api/uaa/v1/file")
public class FileController {
    @Autowired
    private FileService fileService;

    private static final String UPLOAD_FAILED = "文件上传失败";
    private static final String BAD_REQUEST = "非法请求";

    @ApiOperation("上传文件获取文件映射地址")
    @PostMapping("/upload")
    public Result fileUpload(@RequestParam("file") MultipartFile file){
        if (file == null){
            return new Result().error(BAD_REQUEST);
        }
        String url = fileService.uploadFile(file);
        if (StringUtils.isBlank(url)){
            return new Result().error(UPLOAD_FAILED);
        }
        return new Result().ok(url);
    }

    @ApiOperation(value = "上传多文件获取多文件映射地址组合，以','隔开",notes = "注：Swagger-UI不能多文件同时上传，Postman可以")
    @ApiImplicitParam(name = "files",paramType = "formData",allowMultiple=true,required = true,dataType = "file")
    @PostMapping(value = "/upload/all")
    public Result filesUpload(@RequestParam("files") List<MultipartFile> files){
        if (files == null || files.size()<= 0){
            return new Result().error(BAD_REQUEST);
        }
        String urls = fileService.uploadFiles(files);
        if (StringUtils.isBlank(urls)){
            return new Result().error(UPLOAD_FAILED);
        }
        return new Result().ok(urls);
    }
}
